﻿using Fleck;
using FyAutoStartService.Models;
using FySystem.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace FyAutoStartService
{
    internal class WSocketApi
    {
        /// <summary>
        /// 获取所有自启App列表
        /// </summary>
        /// <param name="message"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        internal static List<AppInfo> GetAllApi(WSMessageInfo message, IWebSocketConnection socket)
        {
            try
            {
                return Global.Apps;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 添加自启程序
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static AppInfo AddApp(WSMessageInfo message, IWebSocketConnection socket)
        {
            try
            {
                CheckParam(message);

                AppInfo info = JsonSerializer.Deserialize<AppInfo>(message.val, Global.JsonOpt);
                if (string.IsNullOrWhiteSpace(info.Name))
                    throw new Exception("App名称为空~");
                if (string.IsNullOrWhiteSpace(info.Path))
                    throw new Exception("App路径为空~");
                if (info.IsAutoRestart != null)
                {
                    if (info.IsAutoRestart.Value && info.AutoRestartTime == null)
                        throw new Exception("自动重启时间间隔为空~");
                }
                if (File.Exists(info.Path) == false)
                    throw new Exception("程序文件不存在~");

                if (string.IsNullOrWhiteSpace(info.Id))
                {
                    //如果是新增
                    info.Id = Guid.NewGuid().ToString("N");
                    Global.Apps.Add(info);
                }
                else
                {
                    //如果是修改
                    lock(Global.Apps)
                    {
                        int index = -1;
                        for(int i=0;i<Global.Apps.Count;i++)
                        {
                            if (Global.Apps[i].Id==info.Id)
                            {
                                index = i;
                                break;
                            }
                        }

                        if (index == -1)
                            throw new Exception("未找到自启程序~");

                        //先释放之前的自启程序
                        if (Global.Apps[index].IsRunning.Value == true)
                        {
                            //如果之前程序正在运行
                            Global.Apps[index].Process.Kill();
                            Global.Apps[index].Process.Dispose();
                            Global.Apps[index] = info;
                            AppManager.StartUp(Global.Apps[index]);
                        }
                        else
                        {
                            //如果之前程序不在运行
                            if (Global.Apps[index].Process != null)
                                Global.Apps[index].Process.Dispose();
                            Global.Apps[index] = info;
                        }
                    }
                }

                //保存到文件
                AppManager.SaveApps();

                return info;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 开启程序
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static AppInfo StartApp(WSMessageInfo message, IWebSocketConnection socket)
        {
            AppInfo res = null;
            try
            {
                CheckParam(message);

                lock (Global.Apps)
                {
                    if (Global.Apps.IsNullOrEmpty())
                        throw new Exception("无启动程序~");

                    foreach(var item in Global.Apps)
                    {
                        if (item.Id == message.val)
                        {
                            AppManager.StartUp(item);
                            res = item;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 关闭程序
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static AppInfo StopApp(WSMessageInfo message, IWebSocketConnection socket)
        {
            AppInfo res = null;
            try
            {
                CheckParam(message);

                lock (Global.Apps)
                {
                    if (Global.Apps.IsNullOrEmpty())
                        throw new Exception("无启动程序~");

                    foreach(var item in Global.Apps)
                    {
                        if(item.Id== message.val)
                        {
                            AppManager.CloseApp(item);
                            res = item;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 删除程序
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        internal static AppInfo DeleteApp(WSMessageInfo message, IWebSocketConnection socket)
        {
            AppInfo res = null;
            try
            {
                CheckParam(message);

                lock (Global.Apps)
                {
                    if (Global.Apps.IsNullOrEmpty())
                        throw new Exception("无启动程序~");
                    
                    foreach(var item in Global.Apps)
                    {
                        if(item.Id ==message.val)
                        {
                            res = item;
                            AppManager.DeleteApp(item);
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 登录，登录之后返回一个token
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static void Login(WSMessageInfo message, IWebSocketConnection socket)
        {
            try
            {
                CheckParam(message);

                UserInfo user = JsonSerializer.Deserialize<UserInfo>(message.val);
                if(Authentication.Auth(user) == false)
                {
                    //如果认证失败，直接关闭连接
                    socket.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static void CheckParam(WSMessageInfo message)
        {
            try
            {
                if (message == null)
                    throw new Exception("传入参数为空~");
                if (string.IsNullOrWhiteSpace(message.val))
                    throw new Exception("传入参数为空~");
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
